<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <div class="w-1/4 xl:w-1/5 mr-2 overflow-hidden bg-white h-full">
      <BasicTree
        :title="t('流程监控状态')"
        :clickRowToExpand="true"
        :treeData="treeData"
        :fieldNames="{ key: 'id', title: 'name' }"
        @select="handleSelect"
        :selectedKeys="selectedKeys"
      />
    </div>
    <BasicTable
      @register="registerTable"
      class="w-3/4 xl:w-4/5"
      @selection-change="selectionChange"
    >
      <template #toolbar>
        <LookProcess :taskId="taskId" :processId="processId" @close="reload"
          ><a-button v-auth="'monitor:view'">{{ t('查看') }}</a-button></LookProcess
        >
        <a-button v-auth="'monitor:appointedAuditor'" @click="approveUser" v-if="data.type === 0">{{
          t('指派审核人')
        }}</a-button>
        <a-button v-auth="'monitor:pending'" @click="setSuspended" v-if="data.type === 0">{{
          suspendedTitle
        }}</a-button>
      </template>
      <template #status="{ record }">
        <Tag color="warning" v-if="record.status == ProcessMonitorStatus.SUSPENDED">{{
          t('挂起')
        }}</Tag>
        <Tag color="processing" v-if="record.status == ProcessMonitorStatus.ACTIVE">{{
          t('活动中')
        }}</Tag>
        <Tag color="success" v-if="record.status == ProcessMonitorStatus.COMPLETED">{{
          t('完成')
        }}</Tag>
        <Tag color="error" v-if="record.status == ProcessMonitorStatus.INTERNALLY_TERMINATED">{{
          t('内部终止')
        }}</Tag>
      </template>
      <template #currentProgress="{ record }">
        <a-progress v-if="record.currentProgress" :percent="record.currentProgress" size="small" />
      </template>
    </BasicTable>

    <!-- 指派审核人 -->
    <ApproveProcessMonitorUser
      v-if="data.approvedUserVisible"
      :taskId="taskId"
      :schemaId="schemaId"
      :title="approvedUserTitle"
      @close="
        () => {
          data.approvedUserVisible = false;
          reload();
        }
      "
    />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { reactive, ref } from 'vue';
  import { BasicTree } from '/@/components/Tree';
  import { PageWrapper } from '/@/components/Page';
  import LookProcess from './components/LookProcess.vue';
  import ApproveProcessMonitorUser from './components/flow/ApproveProcessMonitorUser.vue';
  import { getProcessMonitorPage, postSetSuspended } from '/@/api/workflow/monitor';

  import { notification, Tag } from 'ant-design-vue';
  import { ProcessMonitorStatus } from '/@/enums/workflowEnum';
  import { BasicTable, useTable, FormSchema, BasicColumn } from '/@/components/Table';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const configColumns: BasicColumn[] = [
    {
      title: t('流水号'),
      dataIndex: 'serialNumber',
      sorter: {
        multiple: 1,
      },
    },
    {
      title: t('任务'),
      dataIndex: 'currentTaskName',
      width: 120,
      sorter: {
        multiple: 2,
      },
      align: 'left',
    },
    {
      title: t('标题'),
      dataIndex: 'schemaName',
      width: 120,
      sorter: {
        multiple: 3,
      },
      align: 'left',
    },
    {
      title: t('状态'),
      dataIndex: 'status',
      sorter: {
        multiple: 4,
      },
      slots: { customRender: 'status' },
    },
    // {
    //   title: '状态详情',
    //   dataIndex: 'statusMessage',
    // },
    {
      title: t('当前进度'),
      dataIndex: 'currentProgress',
      slots: { customRender: 'currentProgress' },
    },
    {
      title: t('发起人'),
      dataIndex: 'originator',
      align: 'left',
    },
    {
      title: t('时间'),
      width: 160,
      dataIndex: 'createDate',
      align: 'left',
    },
  ];
  const searchFormSchema: FormSchema[] = [
    {
      field: 'keyword',
      label: t('关键字'),
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: t('请输入关键字'),
      },
    },
    {
      field: 'searchDate',
      label: t('时间范围'),
      component: 'RangePicker',
      colProps: { span: 8 },
    },
  ];

  const treeData = [
    {
      key: 0,
      id: 0,
      name: t('未完成'),
      icon: 'ant-design:profile-outlined',
    },
    {
      key: 1,
      id: 1,
      name: t('已完成'),
      icon: 'ant-design:profile-outlined',
    },
  ];
  const selectedKeys = ref([0]);
  const [registerTable, { reload, getSelectRows, clearSelectedRowKeys }] = useTable({
    title: t('流程监控列表'),
    api: getProcessMonitorPage,
    rowKey: 'processId',
    columns: configColumns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      fieldMapToTime: [['searchDate', ['startTime', 'endTime'], 'YYYY-MM-DD', true]],
    },
    rowSelection: {
      type: 'radio',
    },
    beforeFetch: (params) => {
      //发送请求默认新增  左边树结构所选机构id
      return { ...params, type: data.type };
    },
    useSearchForm: true,
    showTableSetting: true,
    striped: false,
    pagination: {
      pageSize: 18,
    },
  });
  let data: {
    type: number;
    approvedUserVisible: boolean;
  } = reactive({
    type: 0,
    approvedUserVisible: false,
  });
  const processId = ref('');
  const taskId = ref('');
  const schemaId = ref('');
  const approvedUserTitle = ref(t('任务'));
  const suspendedTitle = ref(t('挂起'));
  function selectionChange({ keys, rows }) {
    if (keys?.length > 0) {
      processId.value = rows[0].processId;
      taskId.value = rows[0].taskId;
      schemaId.value = rows[0].schemaId;
      approvedUserTitle.value = t('任务-') + rows[0].schemaName + '-' + rows[0].currentTaskName;
      suspendedTitle.value =
        rows[0].status && rows[0].status === ProcessMonitorStatus.SUSPENDED ? t('恢复') : t('挂起');
    } else {
      processId.value = '';
      taskId.value = '';
      schemaId.value = '';
      approvedUserTitle.value = t('任务');
      suspendedTitle.value = t('挂起');
    }
  }

  async function setSuspended() {
    let row = checkSelectSingleRow();
    if (row) {
      let res = await postSetSuspended(row.processId);
      if (res) {
        reload();
        notification.open({
          type: 'success',
          message: suspendedTitle.value,
          description: t('成功'),
        });
      }
    }
    clearSelectedRowKeys();
  }
  function handleSelect(_, e) {
    clearSelectedRowKeys();
    data.type = e.node.key;
    selectedKeys.value = [e.node.key];
    reload();
  }
  function approveUser() {
    let row = checkSelectSingleRow();
    if (row) {
      if (row.taskId) {
        data.approvedUserVisible = true;
      }
    }
  }
  function checkSelectSingleRow() {
    const selectRows = getSelectRows();
    if (selectRows.length > 0) {
      return selectRows[0];
    } else {
      notification.open({
        type: 'error',
        message: t('流程'),
        description: t('请选择一个流程进行'),
      });
      return false;
    }
  }
</script>
